package ru.chaykin.load;
import java.io.BufferedReader;

import ru.chaykin.load.parse.IRegExpsPatternsConsts;
import ru.chaykin.load.parse.MIFParser;
import ru.chaykin.rendering.CullingTextThread;
import ru.chaykin.rendering.CullingThread;
import android.os.SystemClock;
import android.util.Log;



public class LoadDataThread extends Thread {
	private static ILoadDataProgress ldp;
	private static IThreadException te;
	
	private volatile boolean isActive = true;	//Если false, остановим поток
	
	private CullingThread ctt = new CullingTextThread();
	
	private String fName;
	
	public LoadDataThread(IThreadException te, ILoadDataProgress ldp, String fName) {
		super();
		LoadDataThread.ldp = ldp;
		LoadDataThread.te = te;
		this.fName = fName;
	}
	
	public static void setILoadDataProgress(IThreadException te, ILoadDataProgress ldp) {
		LoadDataThread.ldp = ldp;
		LoadDataThread.te = te;
	}
	
	private void update(final String msg) {
		ldp.post(new Runnable() {
			public void run() {
				ldp.onUpdate(msg);
			}
		});
	}
	
	private void complete() {
		ldp.post(new Runnable() {
			public void run() {
				ldp.onComplete();
			}
		});
	}
	
	private void onException(final Exception e) {
		te.runOnUiThread(new Runnable() {
			public void run() {
				te.onException(e);
			}
		});
	}
	
	public void run() {
		Log.d(getClass().getName(), "Thread started");
		String str;
		long count = 0;
		try {
			MIFParser parser = new MIFParser(fName);
			BufferedReader in = parser.getFileReader();
			
			ctt.setPriority(Thread.MIN_PRIORITY );
			ctt.start();
			long time = SystemClock.uptimeMillis();
			while ((str = in.readLine()) != null && isActive) {	
				if (IRegExpsPatternsConsts.B_PLINE_PATT.matcher(str).matches())
					count++;
				//parser.instanceNextObject(str);
				count++;
				if (count % 100 == 0)
					update("Загрузка. Объектов загружено:  " + parser.getObjectsCount());
			}
			Log.d(getClass().getName(), "File loaded in " + 
					(SystemClock.uptimeMillis() - time) / 1000.0 + " sec");
			in.close();
		} catch (Exception e) {
			stopThread();
			onException(e);
		}
		if (isActive)
			complete();
		Log.d(getClass().getName(), "Thread stoped");
	}
	
	public void stopThread() {
		isActive = false;
		ctt.stopThread();//Пользователь отменил задачу
	}
}
